import {reqCartList, reqChangeNum, reqDeleteCartById, reqUpdateCheckedById} from '@/api';
//shopcart模块的小仓库
const state = {
    cart: {}    /*后台返回的购物车数据*/
};
const mutations = {
    CART(state, cart) {
        state.cart = cart
    }
};
const actions = {
    //获取购物车列表数据
    async getCartList({commit}) {
        let result = await reqCartList()
        if (result.code === 0) {
            commit("CART", result.data)
        }
    },
    //删除购物车某一个商品
    async deleteCartListBySkuId({commit}, skuId) {
        let result = await reqDeleteCartById(skuId)
        if (result.code === 0) {
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }
    },
    //修改购物车某一个商品的选中状态
    async updateCheckedById({commit}, {skuId, isChecked}) {
        let result = await reqUpdateCheckedById(skuId, isChecked)
        if (result.code === 0) {
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }
    },
    //修改购物项数量
    async changeCartNum({commit}, {skuId, num}) {
        let result = await reqChangeNum(skuId, num)
        if (result.code === 0) {
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }
    },
    //删除购物车中勾选的商品
    deleteAllCheckedCart({dispatch, getters}) {
        let promiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            if (item.isChecked === 1) {
                let promise = dispatch("deleteCartListBySkuId", item.skuId)
                promiseAll.push(promise)
            }
        })
        //全部成功，返回成功
        return Promise.all(promiseAll)
    },
    //修改全部商品的选中状态
    updateAllCartIsChecked({dispatch,state}, isChecked){
        let promiseAll = []
        state.cartList[0].cartInfoList.forEach(item =>{
            let promise = dispatch("updateCheckedById", {skuId:item.skuId, isChecked})
            promiseAll.push(promise)
        })
        //全部成功，返回成功
        return Promise.all(promiseAll)
    }
};
//计算属性，为了简化数据而生
const getters = {

};
export default {
    state,
    mutations,
    actions,
    getters
}
